import java.util.Stack;

public class StackValidation {
    public static void main(String[] args) {
        int[] pushed = {1, 2, 3, 4, 5};
        int[] popped = {4, 5, 1};
        boolean result = validateStackSequence(pushed, popped);
        System.out.println("输出结果: " + result);
    }

    public static boolean validateStackSequence(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int i = 0; // 指向pushed数组的指针
        for (int num : popped) {
            // 如果栈为空或者栈顶元素不等于当前要匹配的元素，就将pushed数组中的元素入栈
            while (stack.isEmpty() || stack.peek() != num) {
                // 如果pushed数组已经遍历完，就返回false
                if (i == pushed.length) {
                    return false;
                }
                stack.push(pushed[i]);
                i++;
            }
            // 如果栈顶元素等于当前要匹配的元素，就将其出栈
            stack.pop();
        }
        // 如果栈为空，说明所有元素都匹配成功，返回true；否则返回false
        return stack.isEmpty();
    }
}
